var douban = require('../../comm/script/fetch')
var config = require('../../comm/script/config')
var searchByTagUrl = 'https://api.douban.com/v2/movie/search?tag='
Page({
	data: {
		films: [],
		hasMore: true,
		showLoading: true,
		start: 0,
		windowHeight: 0,
		url: '',
		keyword: ''
	},
	onLoad: function(options) {
		var that = this
		that.setData({
			url: options.url,
			keyword: options.keyword,
			title: options.keyword
		})
		douban.search.call(that, that.data.url, that.data.keyword, that.data.start, config.count, function(data) {
			// 字段适配，兼容后端返回和filmList组件展示
			const adapted = (data || []).map(item => ({
				...item,
				images: { large: item.imageUrl || item.image_url || (item.images ? item.images.large : '') },
				rating: { average: parseFloat(item.average_rating || item.averageRating) || 0 },
				genres: Array.isArray(item.genres) ? item.genres : (item.genres ? item.genres.split(',').map(g => g.trim()) : [])
			}));
			that.setData({ films: adapted });
		});
	},
	onShow: function() {
		var that = this
		const windowInfo = wx.getWindowInfo()
		that.setData({
			windowHeight: windowInfo.windowHeight * 2 + 112
		})
	},
	scroll: function(e) {
		console.log(e)
	},
	scrolltolower: function() {
		var that = this
		douban.search.call(that, that.data.url, that.data.keyword, that.data.start, config.count)
	},
	viewFilmDetail: function(e) {
		var id = e.detail.id;
		wx.navigateTo({
			url: "../filmDetail/filmDetail?id=" + id
		})
	},
	onPullDownRefresh: function() {
		var that = this
		that.setData({
			films: [],
			hasMore: true,
			showLoading: true,
			start: 0
		})
		douban.search.call(that, that.data.url, that.data.keyword, that.data.start, config.count)
	},
	viewFilmByTag: function(e) {
		var data = e.currentTarget.dataset
		var keyword = data.tag
		wx.navigateTo({
			url: '../searchResult/searchResult?url=' + encodeURIComponent(searchByTagUrl) + '&keyword=' + keyword
		})
	}
})